package com.smedi.ismedi.progress.core.port.adapter.service.impl;

import com.smedi.ismedi.progress.core.port.adapter.service.FileRemoteApiService;
import com.smedi.ismedi.file.dto.response.FileInfoResponse;
import com.smedi.ismedi.file.feign.RemoteFileFeignApi;
import com.smedi.ismedi.progress.core.infrastructure.constant.EquipmentError;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.BasicError;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 下载附件实现类
 *
 * @author xienannan
 * @date 2021/08/28
 */
@Service
@AllArgsConstructor
public class FileRemoteApiServiceImpl implements FileRemoteApiService {

    private final RemoteFileFeignApi remoteFileFeignApi;

    @Override
    public List<FileInfoResponse> getFileInfoListByKeyList(List<String> KeyList) {
        List<FileInfoResponse> fileInfoResponseList = new ArrayList<>();

        for (String keyTemp : KeyList) {
            FileInfoResponse fileInfoResponse = remoteFileFeignApi.getFileInfo(keyTemp).getData();
            if (fileInfoResponse == null) {
                throw LogicException.raise(EquipmentError.FILES_INFO_MISS);
            }
            fileInfoResponseList.add(fileInfoResponse);
        }

        return fileInfoResponseList;
    }

    @Override
    public String getFilePDFKey(String key) {
        ResponseData<FileInfoResponse> fileInfoResponseResponseData = remoteFileFeignApi.postConvertFileToPdfWithFileKey(key);
        if (!fileInfoResponseResponseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, fileInfoResponseResponseData.getApplication(), String.valueOf(fileInfoResponseResponseData.getErrorMsg()));
        }
        if (null != fileInfoResponseResponseData.getData() && null != fileInfoResponseResponseData.getData().getSignKey()) {
            return remoteFileFeignApi.postConvertFileToPdfWithFileKey(key).getData().getSignKey();
        }
        return null;
    }
}
